package org.demo.url;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

/**
 * Created by tangwy on 2017/8/19.
 */
public class DownloadRunable implements Runnable {
    //private volatile DownloadState downloadState;
    private long position;
    private long end;
    private InputStream inputStream;
    private String filePath;
    public DownloadRunable(long position,long end,InputStream inputStream,String filePath){
        this.position=position;
        this.end=end;
        this.inputStream=inputStream;
        this.filePath=filePath;
        System.out.println("position:"+position+",end="+end);
    }
    @Override
    public void run() {
        //downloadState=DownloadState.RUNNING;
        try {
            inputStream.skip(position);
        } catch (IOException e) {
            //downloadState=DownloadState.EXCEPTION;
            this.close();
            //可以在这里加日志，，记录错误信息
            return;
        }
        byte[]buffer=new byte[4096];
        long contentLength=end-position;
        int readBytes;
        long length=0;
        try(RandomAccessFile randomAccessFile=new RandomAccessFile(filePath,"rw")){
            randomAccessFile.seek(position);
            while ((readBytes=inputStream.read(buffer))>0){
                randomAccessFile.write(buffer,0,readBytes);
                length+=readBytes;
                if(length>contentLength){
                    //System.out.println((length-contentLength));
                    //randomAccessFile.write(buffer,0,(int)(length-contentLength));
                    break;
                }

            }
            System.out.println(Thread.currentThread().getName()+"读取文件长度:"+length);
        } catch (IOException e) {
            //downloadState=DownloadState.EXCEPTION;
            e.printStackTrace();
            //可以在这里加日志，，记录错误信息
        }finally {
            System.out.println(Thread.currentThread().getName()+"运行完成");
            this.close();
            /*if(downloadState==DownloadState.RUNNING){
                downloadState=DownloadState.STOP;
            }*/
        }
    }

    public void close(){
        if(inputStream!=null){
            try {
                inputStream.close();
            } catch (IOException e) {
                //记录异常
                e.printStackTrace();
            }finally {
                inputStream=null;
            }
        }
    }

    /*public DownloadState getDownloadState(){
        return downloadState;
    }*/
}
